package com.daydayup.learn.zikao;

import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.math.BigInteger;

/***
 * 设计一个程序，实现求取两个正整数的最大公约数，要求：在窗口中有三个文本框和两个按钮。第一个按钮上的文字为“最大公约数”，第二个按钮上的文字为“关闭”
 * 当单机按钮“最大公约数”时，能把前两个文本框中的数据的最大公约数存放在第三个文本框中，单机按钮“关闭”，则程序结束
 */
public class FrameTest {

    public static void main(String[] args) {
        Frame frame = new Frame("求最大公约数");
        Label label1 = new Label("整数1:");
        Label label2 = new Label("整数2:");
        Label label3 = new Label("结果:");
        Label label4 = new Label();
        TextField tf1 = new TextField();
        tf1.setPreferredSize(new Dimension(300,50));
        TextField tf2 = new TextField();
        tf2.setPreferredSize(new Dimension(300,50));
        TextField tf3 = new TextField();
        tf3.setPreferredSize(new Dimension(300,50));
        label4.setPreferredSize(new Dimension(300,50));
        label4.setForeground(Color.RED);
        label4.setFont(new Font("宋体",1,15));
        Button b1 = new Button("最大公约数");
        Button b2 = new Button("关闭");
        frame.setBounds(300,500,350,500);
        frame.setLayout(new FlowLayout());
        frame.add(label1);
        frame.add(tf1);
        frame.add(label2);
        frame.add(tf2);
        frame.add(label3);
        frame.add(tf3);
        frame.add(b1);
        frame.add(b2);
        frame.add(label4);
        b1.addActionListener(e -> {
            String v1 = tf1.getText();
            String v2 = tf2.getText();
            try {
                label4.setText("");
                BigInteger n1 = new BigInteger(v1);
                BigInteger n2 = new BigInteger(v2);
                BigInteger gcd = n1.gcd(n2);
                tf3.setText(""+gcd.intValue());
            } catch (Exception ex) {
                label4.setText("异常信息:"+ex.getMessage());
            }
        });
        b2.addActionListener(e -> {
            System.exit(1);
        });
        frame.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {
                System.out.println("窗口已打开");
            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭中......");
                System.exit(100);
            }

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("窗口已关闭");
            }

            @Override
            public void windowIconified(WindowEvent e) {

            }

            @Override
            public void windowDeiconified(WindowEvent e) {

            }

            @Override
            public void windowActivated(WindowEvent e) {

            }

            @Override
            public void windowDeactivated(WindowEvent e) {

            }
        });
        frame.setVisible(true);
    }
}
